package com.chen.kafla.log.listener;

import com.alibaba.fastjson.JSONObject;
import com.chen.kafla.log.entity.MessageEntity;
import com.chen.kafla.log.repository.MessageMapper;
import lombok.extern.log4j.Log4j2;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
@Transactional(rollbackFor = Exception.class)
@Log4j2
public class KafkaMessageListener {

    @Autowired
    private MessageMapper mapper;

    /**
     * 监听日志
     *
     * @param record
     */
    @KafkaListener(topics = {"errorlog"}, groupId = "test-consumer-group")
    public void listener(ConsumerRecord<String, String> record) {
        String value = record.value();
        MessageEntity entity = JSONObject.parseObject(value, MessageEntity.class);
        entity.setId(null);
        entity.setCreateTime(new Date());
        int insert = mapper.insert(entity);
        if (insert > 0) {
            log.info("记录成功 {} - {} - {}", entity.getErrorTitle(), entity.getErrorCode(), entity.getServerName());
        }
    }

}
